package com.apollow.oschina.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.apollow.oschina.R;
import com.apollow.oschina.base.BaseFragment;
import com.apollow.oschina.base.Global;
import com.apollow.oschina.ui.BlogActivity;
import com.apollow.oschina.ui.CollectActivity;
import com.apollow.oschina.ui.FollowFansActivity;
import com.apollow.oschina.ui.InformationActivity;
import com.apollow.oschina.ui.UserInfoActivity;
import com.apollow.oschina.util.QRCodeUtil;
import com.apollow.oschina.widget.CustomPopDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by bobo on 2017/1/12.
 */

public class MyFragment extends BaseFragment {

    @BindView(R.id.civ_header)
    CircleImageView mCivHeader;
    @BindView(R.id.iv_qr_code)
    ImageView mIvQrCode;
    @BindView(R.id.tv_integral_count)
    TextView mTvIntegralCount;
    @BindView(R.id.tv_collect_count)
    TextView mTvCollectCount;
    @BindView(R.id.tv_collect)
    TextView mTvCollect;
    @BindView(R.id.ll_collect)
    LinearLayout mLlCollect;
    @BindView(R.id.tv_follw_count)
    TextView mTvFollwCount;
    @BindView(R.id.ll_follow)
    LinearLayout mLlFollow;
    @BindView(R.id.tv_fans_count)
    TextView mTvFansCount;
    @BindView(R.id.ll_fans)
    LinearLayout mLlFans;
    @BindView(R.id.ll_information)
    LinearLayout mLlInformation;
    @BindView(R.id.ll_blog)
    LinearLayout mLlBlog;
    @BindView(R.id.tv_my_item)
    TextView mTvMyItem;
    private String mState;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = Global.inflate(R.layout.fragment_my, container);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initData();
        initEvent();
    }

    private void initEvent() {

    }

    private void initData() {

    }

    private void initView() {

    }

    @OnClick({R.id.iv_qr_code, R.id.ll_collect, R.id.ll_follow, R.id.ll_fans, R.id.ll_information, R.id.ll_blog,R.id.civ_header})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_qr_code:
                gen();
                break;
            case R.id.ll_collect:
                Intent collectIntent = new Intent(getActivity(),CollectActivity.class);
                startActivity(collectIntent);
                break;
            case R.id.ll_follow:
                Intent intent = new Intent(getActivity(),FollowFansActivity.class);
                mState = "关注";
                intent.putExtra("state",mState);
                startActivity(intent);
                break;
            case R.id.ll_fans:
                Intent fansIntent = new Intent(getActivity(),FollowFansActivity.class);
                mState = "粉丝";
                fansIntent.putExtra("state",mState);
                startActivity(fansIntent);
                break;
            case R.id.ll_information:
                Intent InfoIntent = new Intent(getActivity(),InformationActivity.class);
                startActivity(InfoIntent);
                break;
            case R.id.civ_header:
                Intent userIntent = new Intent(getActivity(),UserInfoActivity.class);
                startActivity(userIntent);
                break;
            case R.id.ll_blog:
                Intent blogIntent = new Intent(getActivity(), BlogActivity.class);
                startActivity(blogIntent);
                break;
        }
    }

    private void gen() {
        String content="广州黑马安卓11期就是牛逼";
        String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/md5";
        Bitmap logo = BitmapFactory.decodeResource(getActivity().getResources(),0);
        QRCodeUtil.createQRImage(content,250,250,logo,path);
        final Bitmap bitmap = BitmapFactory.decodeFile(path);// 这里是获取图片Bitmap，也可以传入其他参数到Dialog中
//        Drawable drawable = Drawable.createFromPath(path);
//        BitmapDrawable drawable = new BitmapDrawable(getResources(),bitmap);
        CustomPopDialog dialog = new CustomPopDialog(getContext());
        dialog.setBitmap(bitmap);
//        dialog.setDrawable(drawable);
        dialog.setOnLongClickListener(new CustomPopDialog.onLongClickListener() {
            @Override
            public void onLongClick() {
                saveImageView(bitmap);
            }
        });
        dialog.show();

    }

    private class SaveObservable implements Observable.OnSubscribe<String> {

        private Bitmap drawingCache = null;

        public SaveObservable(Bitmap drawingCache) {
            this.drawingCache = drawingCache;
        }

        @Override
        public void call(Subscriber<? super String> subscriber) {
            if (drawingCache == null) {
                subscriber.onError(new NullPointerException("imageview的bitmap获取为null,请确认imageview显示图片了"));
            } else {
                try {
                    File imageFile = new File(Environment.getExternalStorageDirectory(), "qrcode.jpg");
                    FileOutputStream outStream;
                    outStream = new FileOutputStream(imageFile);
                    drawingCache.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
                    subscriber.onNext(Environment.getExternalStorageDirectory().getPath());
                    subscriber.onCompleted();
                    outStream.flush();
                    outStream.close();
                } catch (IOException e) {
                    subscriber.onError(e);
                }
            }
        }
    }

    private class SaveSubscriber extends Subscriber<String> {

        @Override
        public void onCompleted() {
            Toast.makeText(getContext(), "保存成功", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(Throwable e) {
            Log.i(getClass().getSimpleName(), e.toString());
            Toast.makeText(getContext(), "保存失败——> " + e.toString(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNext(String s) {
            Toast.makeText(getContext(), "保存路径为：-->  " + s, Toast.LENGTH_SHORT).show();
        }
    }


    private void saveImageView(Bitmap drawingCache) {
        Observable.create(new SaveObservable(drawingCache))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SaveSubscriber());
    }

    /**
     * 某些机型直接获取会为null,在这里处理一下防止国内某些机型返回null
     */
    private Bitmap getViewBitmap(View view) {
        if (view == null) {
            return null;
        }
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        return bitmap;
    }
}
